package services

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"strings"

	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
)

// GetAccountHistoryList 查询光子易账户账单流水
func GetAccountHistoryList(ctx context.Context, client *photonpay.PhotonPayClient, params models.AccountHistoryQueryParams) (*models.AccountHistoryListResponse, error) {
	query := url.Values{}
	query.Set("transactedAtStart", params.TransactedAtStart)
	query.Set("transactedAtEnd", params.TransactedAtEnd)
	if params.MemberID != "" {
		query.Set("memberId", params.MemberID)
	}
	if params.AccountTransactionID != "" {
		query.Set("accountTransactionId", params.AccountTransactionID)
	}
	if params.Currency != "" {
		query.Set("currency", params.Currency)
	}
	if params.AccountType != "" {
		query.Set("accountType", params.AccountType)
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}
	if params.AccountNo != "" {
		query.Set("accountNo", params.AccountNo)
	}
	if len(params.TxnType) > 0 {
		query.Set("txnType", strings.Join(params.TxnType, ","))
	}
	if params.PageSize > 0 {
		query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	}
	if params.PageIndex > 0 {
		query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	}

	path := "/wallet/openApi/v4/account/history"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get account history list failed: %v", err)
	}

	var result models.AccountHistoryListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get account history list failed: %s", result.Msg)
	}

	return &result, nil
}

// GetAccountBalance 查询实时账户余额
func GetAccountBalance(ctx context.Context, client *photonpay.PhotonPayClient, params models.AccountBalanceQueryParams) (*models.AccountBalanceResponse, error) {
	query := url.Values{}
	query.Set("currency", params.Currency)
	if params.AccountNo != "" {
		query.Set("accountNo", params.AccountNo)
	}
	if params.MemberID != "" {
		query.Set("memberId", params.MemberID)
	}
	if params.AccountType != "" {
		query.Set("accountType", params.AccountType)
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}

	path := "/wallet/openApi/v4/account/single"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}
	fmt.Println("path", path)
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get account balance failed: %v", err)
	}

	var result models.AccountBalanceResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get account balance failed: %s", result.Msg)
	}

	return &result, nil
}

// GetAccountList 查询金额账户列表
func GetAccountList(ctx context.Context, client *photonpay.PhotonPayClient, params models.AccountListQueryParams) (*models.AccountListResponse, error) {
	query := url.Values{}
	if params.AccountNo != "" {
		query.Set("accountNo", params.AccountNo)
	}
	if params.MemberID != "" {
		query.Set("memberId", params.MemberID)
	}
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}

	path := "/wallet/openApi/v4/account/list"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}
	fmt.Println("path", path)
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get account list failed: %v", err)
	}

	var result models.AccountListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get account list failed: %s", result.Msg)
	}
	fmt.Println("result", result)
	return &result, nil
}

// GetMatrixAccountList 查询matrix账户信息
func GetMatrixAccountList(ctx context.Context, client *photonpay.PhotonPayClient, params models.MatrixAccountQueryParams) (*models.MatrixAccountListResponse, error) {
	query := url.Values{}
	query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	if params.MatrixAccount != "" {
		query.Set("matrixAccount", params.MatrixAccount)
	}
	if params.CreatedAtStart != "" {
		query.Set("createdAtStart", params.CreatedAtStart)
	}
	if params.CreatedAtEnd != "" {
		query.Set("createdAtEnd", params.CreatedAtEnd)
	}

	path := "/matrix/openApi/v4/getPageMatrixAccountInfo"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get matrix account list failed: %v", err)
	}

	var result models.MatrixAccountListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get matrix account list failed: %s", result.Msg)
	}

	return &result, nil
}

// GetFundTransferList 查询资金调拨明细
func GetFundTransferList(ctx context.Context, client *photonpay.PhotonPayClient, params models.FundTransferListQueryParams) (*models.FundTransferListResponse, error) {
	query := url.Values{}
	if params.PageIndex > 0 {
		query.Set("pageIndex", fmt.Sprintf("%d", params.PageIndex))
	}
	if params.PageSize > 0 {
		query.Set("pageSize", fmt.Sprintf("%d", params.PageSize))
	}
	if params.CreatedAtStart != "" {
		query.Set("createdAtStart", params.CreatedAtStart)
	}
	if params.CreatedAtEnd != "" {
		query.Set("createdAtEnd", params.CreatedAtEnd)
	}
	if params.CompletedAtStart != "" {
		query.Set("completedAtStart", params.CompletedAtStart)
	}
	if params.CompletedAtEnd != "" {
		query.Set("completedAtEnd", params.CompletedAtEnd)
	}
	if params.Status != "" {
		query.Set("status", params.Status)
	}
	if params.RequestNo != "" {
		query.Set("requestNo", params.RequestNo)
	}
	if params.TransactionId != "" {
		query.Set("transactionId", params.TransactionId)
	}
	if params.Direction != "" {
		query.Set("direction", params.Direction)
	}
	if params.MemberId != "" {
		query.Set("memberId", params.MemberId)
	}

	path := "/matrix/openApi/v4/connectMember/fundTransferList"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get fund transfer list failed: %v", err)
	}

	var result models.FundTransferListResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	if result.Code != "0000" {
		return nil, fmt.Errorf("get fund transfer list failed: %s", result.Msg)
	}

	return &result, nil
}

// CreateMatrixAccount 创建matrix账户，bodyBytes 用于签名和请求体
func CreateMatrixAccount(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/matrix/openApi/v4/createMatrixAccount"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("参数", ctx, path, string(bodyBytes))
	if err != nil {
		return nil, fmt.Errorf("create matrix account failed: %v", err)
	}
	return resp, nil
}

// EditMatrixAccount 编辑matrix账户信息，bodyBytes 用于签名和请求体
func EditMatrixAccount(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/matrix/openApi/v4/editMatrixAccountName"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("参数", ctx, path, string(bodyBytes))
	if err != nil {
		return nil, fmt.Errorf("edit matrix account failed: %v", err)
	}
	return resp, nil
}

// MatrixTransfer 资金划转，bodyBytes 用于签名和请求体
func MatrixTransfer(ctx context.Context, client *photonpay.PhotonPayClient, bodyBytes []byte) ([]byte, error) {
	path := "/matrix/openApi/v4/transfer"

	resp, err := client.PostWithRawBody(ctx, path, bodyBytes)
	fmt.Print("参数", ctx, path, string(bodyBytes))
	if err != nil {
		return nil, fmt.Errorf("matrix transfer failed: %v", err)
	}
	return resp, nil
}
